package com.study.framework.listener;

import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.listener.SaTokenListener;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.study.common.constant.CacheConstants;
import com.study.common.core.domain.dto.AppUserOnlineDTO;
import com.study.common.core.domain.dto.UserOnlineDTO;
import com.study.common.core.domain.model.AppLoginUser;
import com.study.common.core.domain.model.LoginUser;
import com.study.common.enums.UserType;
import com.study.common.exception.ServiceException;
import com.study.common.helper.AppLoginHelper;
import com.study.common.helper.LoginHelper;
import com.study.common.utils.ServletUtils;
import com.study.common.utils.ip.AddressUtils;
import com.study.common.utils.redis.RedisUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * 用户行为 侦听器的实现
 * <p>
 * 在用户登录、退出、被踢下线等关键性操作时进行一些AOP操作
 */
@RequiredArgsConstructor
@Component
@Slf4j
public class UserActionListener implements SaTokenListener {

    private final SaTokenConfig tokenConfig;

    /**
     * 每次登录时触发
     */
    @Override
    public void doLogin(String loginType, Object loginId, String tokenValue, SaLoginModel loginModel) {
        UserType userType = UserType.getUserType(loginId.toString());
        UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = ServletUtils.getClientIP();
        switch (userType) {
            case SYS_USER:
                LoginUser user = LoginHelper.getLoginUser();
                UserOnlineDTO dto = new UserOnlineDTO();
                dto.setIpaddr(ip);
                dto.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
                dto.setBrowser(userAgent.getBrowser().getName());
                dto.setOs(userAgent.getOs().getName());
                dto.setLoginTime(System.currentTimeMillis());
                dto.setTokenId(tokenValue);
                dto.setUserName(user.getUsername());
                dto.setDeptName(user.getDeptName());
                if (tokenConfig.getTimeout() == -1) {
                    RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, dto);
                } else {
                    RedisUtils.setCacheObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue, dto, Duration.ofSeconds(tokenConfig.getTimeout()));
                }
                log.info("<login> pc user doLogin, userId:{}, token:{}" , loginId, tokenValue);
                break;
            case APP_USER:
                AppLoginUser loginUser = AppLoginHelper.getLoginUser();
                AppUserOnlineDTO appUser = new AppUserOnlineDTO();
                appUser.setIpaddr(ip);
                appUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
                appUser.setBrowser(userAgent.getBrowser().getName());
                appUser.setOs(userAgent.getOs().getName());
                appUser.setLoginTime(System.currentTimeMillis());
                appUser.setTokenId(tokenValue);
                appUser.setUserName(loginUser.getUserPhone());
                if (tokenConfig.getTimeout() == -1) {
                    RedisUtils.setCacheObject(CacheConstants.APP_ONLINE_TOKEN_KEY + tokenValue, appUser);
                } else {
                    RedisUtils.setCacheObject(CacheConstants.APP_ONLINE_TOKEN_KEY + tokenValue, appUser, Duration.ofSeconds(tokenConfig.getTimeout()));
                }
                log.info("<login> app user doLogin, userId:{}, token:{}" , loginId, tokenValue);
                break;
            default:
                throw new ServiceException("登录请求异常, 未实现");
        }
    }

    /**
     * 每次注销时触发
     */
    @Override
    public void doLogout(String loginType, Object loginId, String tokenValue) {
        RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
        log.info("user doLogout, userId:{}, token:{}" , loginId, tokenValue);
    }

    /**
     * 每次被踢下线时触发
     */
    @Override
    public void doKickout(String loginType, Object loginId, String tokenValue) {
        RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
        log.info("user doLogoutByLoginId, userId:{}, token:{}" , loginId, tokenValue);
    }

    /**
     * 每次被顶下线时触发
     */
    @Override
    public void doReplaced(String loginType, Object loginId, String tokenValue) {
        RedisUtils.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + tokenValue);
        log.info("user doReplaced, userId:{}, token:{}" , loginId, tokenValue);
    }

    /**
     * 每次被封禁时触发
     */
    @Override
    public void doDisable(String loginType, Object loginId, String service, int level, long disableTime) {
    }

    /**
     * 每次被解封时触发
     */
    @Override
    public void doUntieDisable(String loginType, Object loginId, String service) {
    }

    /**
     * 每次打开二级认证时触发
     */
    @Override
    public void doOpenSafe(String loginType, String tokenValue, String service, long safeTime) {
    }

    /**
     * 每次创建Session时触发
     */
    @Override
    public void doCloseSafe(String loginType, String tokenValue, String service) {
    }

    /**
     * 每次创建Session时触发
     */
    @Override
    public void doCreateSession(String id) {
    }

    /**
     * 每次注销Session时触发
     */
    @Override
    public void doLogoutSession(String id) {
    }

    /**
     * 每次Token续期时触发
     */
    @Override
    public void doRenewTimeout(String tokenValue, Object loginId, long timeout) {
    }
}
